package com.demo.practiceui.views.chart;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * 仪表盘
 * 核心知识点：
 * 1. canvas.drawArc() - 绘制圆弧背景
 * 2. 三角函数 - 计算指针端点坐标
 * 3. Path - 绘制复杂形状（指针）
 * 4. 角度映射 - 数值映射到角度
 */
public class DashboardView extends View {

    // 数据
    private float currentValue = 65;   // 当前值
    private float maxValue = 100;      // 最大值
    private float minValue = 0;        // 最小值

    // 画笔
    private Paint arcPaint;            // 圆弧画笔
    private Paint pointerPaint;        // 指针画笔
    private Paint textPaint;           // 文字画笔
    private Paint scalePaint;          // 刻度画笔

    // 尺寸
    private int width;
    private int height;
    private float centerX;
    private float centerY;
    private float radius;

    // 角度范围（仪表盘通常是180度或270度）
    private float startAngle = 135;    // 起始角度
    private float sweepAngle = 270;    // 扫过角度

    private RectF rectF;
    private Path pointerPath;

    public DashboardView(Context context) {
        this(context, null);
    }

    public DashboardView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DashboardView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 圆弧画笔
        arcPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        arcPaint.setStyle(Paint.Style.STROKE);
        arcPaint.setStrokeWidth(40f);
        arcPaint.setStrokeCap(Paint.Cap.ROUND);

        // 指针画笔
        pointerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        pointerPaint.setColor(Color.parseColor("#FF5722"));
        pointerPaint.setStyle(Paint.Style.FILL);

        // 文字画笔
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.parseColor("#333333"));
        textPaint.setTextSize(48f);
        textPaint.setTextAlign(Paint.Align.CENTER);

        // 刻度画笔
        scalePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        scalePaint.setColor(Color.parseColor("#999999"));
        scalePaint.setStrokeWidth(3f);
        scalePaint.setTextSize(28f);
        scalePaint.setTextAlign(Paint.Align.CENTER);

        rectF = new RectF();
        pointerPath = new Path();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST) {
            width = 600;
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = 600;
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        centerX = width / 2f;
        centerY = height / 2f + 50;  // 稍微向下偏移
        radius = Math.min(width, height) / 2f - 100;

        rectF.set(centerX - radius, centerY - radius,
                centerX + radius, centerY + radius);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 1. 绘制背景圆弧
        drawBackgroundArc(canvas);

        // 2. 绘制进度圆弧
        drawProgressArc(canvas);

        // 3. 绘制刻度
        drawScale(canvas);

        // 4. 绘制指针
        drawPointer(canvas);

        // 5. 绘制中心圆点
       // drawCenterCircle(canvas);

        // 6. 绘制数值文字
        drawValueText(canvas);
    }

    /**
     * 绘制背景圆弧
     */
    private void drawBackgroundArc(Canvas canvas) {
        arcPaint.setColor(Color.parseColor("#E0E0E0"));
        canvas.drawArc(rectF, startAngle, sweepAngle, false, arcPaint);
    }

    /**
     * 绘制进度圆弧（彩色渐变效果）
     */
    private void drawProgressArc(Canvas canvas) {
        // 计算当前值对应的角度
        float valueAngle = ((currentValue - minValue) / (maxValue - minValue)) * sweepAngle;

        // 根据进度使用不同颜色
        if (currentValue < 30) {
            arcPaint.setColor(Color.parseColor("#4CAF50"));  // 绿色
        } else if (currentValue < 70) {
            arcPaint.setColor(Color.parseColor("#FFC107"));  // 黄色
        } else {
            arcPaint.setColor(Color.parseColor("#FF5722"));  // 红色
        }

        canvas.drawArc(rectF, startAngle, valueAngle, false, arcPaint);
    }

    /**
     * 绘制刻度
     */
    private void drawScale(Canvas canvas) {
        int scaleCount = 10;  // 10个刻度
        for (int i = 0; i <= scaleCount; i++) {
            float angle = startAngle + (sweepAngle * i / scaleCount);
            float angleRad = (float) Math.toRadians(angle);

            // 计算刻度线的起点和终点
            float startX = centerX + (float) (radius - 50) * (float) Math.cos(angleRad);
            float startY = centerY + (float) (radius - 50) * (float) Math.sin(angleRad);
            float endX = centerX + (float) (radius - 70) * (float) Math.cos(angleRad);
            float endY = centerY + (float) (radius - 70) * (float) Math.sin(angleRad);

            canvas.drawLine(startX, startY, endX, endY, scalePaint);

            // 绘制刻度数值
            float value = minValue + (maxValue - minValue) * i / scaleCount;
            float textX = centerX + (float) (radius - 100) * (float) Math.cos(angleRad);
            float textY = centerY + (float) (radius - 100) * (float) Math.sin(angleRad) + 10;
            canvas.drawText(String.format("%.0f", value), textX, textY, scalePaint);
        }
    }

    /**
     * 绘制指针
     */
    private void drawPointer(Canvas canvas) {
        // 计算指针角度
        float valueAngle = startAngle + ((currentValue - minValue) / (maxValue - minValue)) * sweepAngle;
        float angleRad = (float) Math.toRadians(valueAngle);

        // 指针长度
        float pointerLength = radius - 80;
        float pointerWidth = 15f;

        // 计算指针端点
        float endX = centerX + pointerLength * (float) Math.cos(angleRad);
        float endY = centerY + pointerLength * (float) Math.sin(angleRad);

        // 计算指针两侧点（垂直于指针方向）
        float perpAngle1 = angleRad - (float) Math.PI / 2;
        float perpAngle2 = angleRad + (float) Math.PI / 2;

        float side1X = centerX + pointerWidth * (float) Math.cos(perpAngle1);
        float side1Y = centerY + pointerWidth * (float) Math.sin(perpAngle1);
        float side2X = centerX + pointerWidth * (float) Math.cos(perpAngle2);
        float side2Y = centerY + pointerWidth * (float) Math.sin(perpAngle2);

        // 绘制三角形指针
        pointerPath.reset();
        pointerPath.moveTo(endX, endY);
        pointerPath.lineTo(side1X, side1Y);
        pointerPath.lineTo(side2X, side2Y);
        pointerPath.close();

        canvas.drawPath(pointerPath, pointerPaint);
    }

    /**
     * 绘制中心圆点
     */
    private void drawCenterCircle(Canvas canvas) {
        pointerPaint.setColor(Color.parseColor("#FF5722"));
        canvas.drawCircle(centerX, centerY, 20, pointerPaint);

        pointerPaint.setColor(Color.WHITE);
        canvas.drawCircle(centerX, centerY, 10, pointerPaint);
    }

    /**
     * 绘制数值文字
     */
    private void drawValueText(Canvas canvas) {
        textPaint.setTextSize(72f);
        textPaint.setColor(Color.parseColor("#333333"));
        canvas.drawText(String.format("%.1f", currentValue), centerX, centerY + 80, textPaint);

        textPaint.setTextSize(32f);
        textPaint.setColor(Color.parseColor("#999999"));
        canvas.drawText("km/h", centerX, centerY + 120, textPaint);
    }

    /**
     * 设置当前值
     */
    public void setValue(float value) {
        this.currentValue = Math.max(minValue, Math.min(maxValue, value));
        invalidate();
    }

    /**
     * 设置数值范围
     */
    public void setRange(float minValue, float maxValue) {
        this.minValue = minValue;
        this.maxValue = maxValue;
        invalidate();
    }
}

